package com.blockmeta.bbs.overallserviceapplication.activity.login;

import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blockmeta.bbs.baselibrary.provider.IApplicationProvider;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseCodeResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.pojo.UserPhonePOJO;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.AppCode;
import com.blockmeta.bbs.businesslibrary.util.DeviceUtil;
import com.blockmeta.bbs.overallserviceapplication.R;
import com.blockmeta.bbs.overallserviceapplication.R2;
import com.blockmeta.bbs.overallserviceapplication.net.SmsEcodeHelper;
import com.blockmeta.bbs.overallserviceapplication.net.api.NetApi;
import com.blockmeta.bbs.businesslibrary.pojo.LoginPOJO;
import com.blockmeta.bbs.overallserviceapplication.umeng.ThirdLoginDataPOJO;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * 三方登陆后绑定手机号
 */
public class BindPhoneActivity extends BaseActivity {
    @BindView(R2.id.iv_head_portrait)
    ImageView mIvHeadPortrait;
    @BindView(R2.id.edit_phone_number)
    EditText mEditPhoneNumber;
    @BindView(R2.id.btn_verification_code)
    Button mBtnVerificationCode;
    @BindView(R2.id.edit_verification_code)
    EditText mEditVerificationCode;
    @BindView(R2.id.voice_code)
    LinearLayout voiceCode;
    @BindView(R2.id.voice_code_tv)
    LinearLayout voiceCodeTv;
    @BindView(R2.id.btn_bind)
    Button mBtnBind;
    @BindView(R2.id.tv_bind_switch)
    TextView mTvBindSwitch;
    @BindView(R2.id.btn_postpone)
    Button mBtnPostpone;

    private Context mContext;

    private HashMap<String, String> ecodeMap = new HashMap<>();
    private String openId = ThirdLoginDataPOJO.getINSTANCE().getUid();
    private String unionId = ThirdLoginDataPOJO.getINSTANCE().getUnionid();
    private String name = ThirdLoginDataPOJO.getINSTANCE().getName();
    private String avatar = ThirdLoginDataPOJO.getINSTANCE().getIconUrl();
    private String type = ThirdLoginDataPOJO.getINSTANCE().getType();
    private String stoken = ThirdLoginDataPOJO.getINSTANCE().getStoken();
    private SmsEcodeHelper mHelper;

    @Override
    protected boolean showTitle() {
        return true;
    }

    @Override
    public View setView() {
        mContext = BindPhoneActivity.this;
        setTitleText("");
        return LayoutInflater.from(mContext).inflate(R.layout.activity_bind_phone, null);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Glide.with(this).load(avatar).into(mIvHeadPortrait);//设置头像
        mHelper = new SmsEcodeHelper(mContext, mBtnVerificationCode);
    }

    @OnClick({R2.id.btn_verification_code, R2.id.btn_bind, R2.id.tv_bind_switch, R2.id.btn_postpone, R2.id.voice_code})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.btn_verification_code) {
            getEcode();

        } else if (i == R.id.btn_bind) {
            String phone = mEditPhoneNumber.getText().toString();
            String code = mEditVerificationCode.getText().toString();
            if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(code)) {
                ToastUtil.show(mContext, "输入的内容不能为空");
            } else {
                BindOrPostpone(openId, unionId, name, avatar, type, 0, phone, code,stoken);
            }

        } else if (i == R.id.tv_bind_switch) {
            startActivity(new Intent(this, BindAccountActivity.class));
            finish();

        } else if (i == R.id.btn_postpone) {
            BindOrPostpone(openId, unionId, name, avatar, type, 1, null, null,stoken);

        } else if (i == R.id.voice_code) {
            sendVoiceCode();

        } else {
        }
    }

    /**
     * 绑定手机或者推迟绑定，
     *
     * @param openId           三方登陆的唯一标识
     * @param nickName         昵称
     * @param avatar           头像链接
     * @param type             使用哪个三方平台登陆的 weixin qq weibo
     * @param register         推迟绑定时register=1 其它=0
     * @param phone            手机号
     * @param verificationCode 6位验证码
     */
    private void BindOrPostpone(String openId, String unionId, String nickName, String avatar, String type, int register, String phone, String verificationCode,String stoken) {
        HashMap<String, String> checkMap = new HashMap<>();
        IApplicationProvider provider = RouterHelper.getProvider(RouterPath.APPLICATION_PROVIDER);
        String myAppCode = AppCode.getMyAppCode(provider.getProjectBuildInfo().application_id);

        checkMap.put("openid", openId);
        checkMap.put("unionid", unionId);
        checkMap.put("nickname", nickName);
        checkMap.put("avatar", avatar);
        checkMap.put("type", type);
        checkMap.put("stoken",stoken);
        checkMap.put("register", register + "");
        checkMap.put("mobile", phone);
        checkMap.put("code", verificationCode);
        checkMap.put("device_id", DeviceUtil.getIMEI());
        checkMap.put("product_code", myAppCode);
        checkMap.put("source","app");
        checkMap.put("bind_type","3");

        RetrofitFactory.getRootRetrofit().create(NetApi.SocialBind.class)
                .bindSocial(RequestBody.create(NetApi.sMediaType,new Gson().toJson(checkMap)))
                .compose(this.<BaseCodeResponse<LoginPOJO>>bindToLifecycle())
                .compose(RxUtil.<BaseCodeResponse<LoginPOJO>>rxSchedulerHelper())
                .compose(RxUtil.<LoginPOJO>commonResultByCode())
                .subscribe(new CommonSubscriber<LoginPOJO>(mContext) {
                    @Override
                    public void onNext(LoginPOJO loginPOJO) {
                        saveUserInfo(loginPOJO);
                        finish();
                    }
                });
    }

    private void getEcode() {
        if (mEditPhoneNumber.getText().toString().length() != 11) {
            ToastUtil.show(mContext,"手机号码格式错误");
        } else {
            HashMap<String, String> ecodeMap = new HashMap<>();
            ecodeMap.put("mobile", mEditPhoneNumber.getText().toString());
            mHelper.DealWithEcode(ecodeMap);
            mHelper.setCount(new SmsEcodeHelper.CountDownTimerCallBack() {
                @Override
                public void countdowncallback(CountDownTimer countDownTimer) {
                    countDownTimer.cancel();
                    countDownTimer.start();
                }
            });
            mHelper.setTimeEquals(new SmsEcodeHelper.TimeEquals() {
                @Override
                public void timeequals(int time) {
                    if (time == 45) {
                        if (voiceCodeTv!=null){
                            voiceCodeTv.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
        }
    }

    /**
     * 保存用户信息，进行持久化
     */
    /**
     * 保存用户信息，进行持久化
     */
    private void saveUserInfo(LoginPOJO loginPOJO) {
        if (loginPOJO.userInfo==null){return;}
        UserPhonePOJO userPhonePOJO = new UserPhonePOJO();
        userPhonePOJO.setEmail(loginPOJO.userInfo.email);
        userPhonePOJO.setMobile(loginPOJO.userInfo.mobile);
        userPhonePOJO.setUid(Integer.valueOf(loginPOJO.userInfo.uid));
        userPhonePOJO.setUserName(loginPOJO.userInfo.userName);
        userPhonePOJO.setToken(loginPOJO.token);

        AccountHelper.doLogin(userPhonePOJO);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return keyCode == KeyEvent.KEYCODE_BACK || super.onKeyDown(keyCode, event);
    }

    /**
     * 发送语音验证码
     * 在发送短信验证码之后大概10秒钟之后
     */
    private void sendVoiceCode() {
        if (mEditPhoneNumber.getText().toString().length() != 11) {
            ToastUtil.show(mContext,"手机号码格式错误");
        } else {
            HashMap<String, String> ecodeMap = new HashMap<>();
            ecodeMap.put("mobile", mEditPhoneNumber.getText().toString());
            ecodeMap.put("type_id", "2");
            mHelper.DealWithEcode(ecodeMap);
            mHelper.setCount(new SmsEcodeHelper.CountDownTimerCallBack() {
                @Override
                public void countdowncallback(CountDownTimer countDownTimer) {
                    countDownTimer.cancel();
                    countDownTimer.start();
                }
            });
            mHelper.setTimeEquals(new SmsEcodeHelper.TimeEquals() {
                @Override
                public void timeequals(int time) {
                    if (voiceCode != null) {
                        if (time < 5) {
                            voiceCode.setClickable(true);
                        } else {
                            voiceCode.setClickable(false);
                        }
                    }
                }
            });

        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHelper!=null){
            mHelper.releaseCountDown();
        }
    }
}
